package com.feijin.testwisdomzonedemo.net;

import android.text.TextUtils;

import com.lgc.garylianglib.net.NetworkUtils;
import com.lgc.garylianglib.util.config.MyApplication;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * <pre>
 *     author : feijin_lgc
 *     e-mail : 595184932@qq.com
 *     time   : 2018/1/23 16:53
 *     desc   :   缓存器
 *     version: 1.0
 * </pre>
 */

public class CacheInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (!NetworkUtils.isNetworkAvailable(MyApplication.getInstance()) && RMer.isAllowCache) {
            /**
             * 离线缓存控制  总的缓存时间=在线缓存时间+设置离线缓存时间
             */
            int maxStale = 60 * 60 * 24 * 28; // 离线时缓存保存4周,单位:秒
            CacheControl tempCacheControl = new CacheControl.Builder()
                    .onlyIfCached()
                    .maxStale(maxStale, TimeUnit.SECONDS)
                    .build();
            request = request.newBuilder()
                    .cacheControl(tempCacheControl)
                    .build();
        }
        Response response = chain.proceed(request);
//        if (RMer.isAllowCache) {

        String serverCache = response.header("Cache-Control");
        // 如果服务端设置相应的缓存策略那么遵从服务端的不做修改
        if (TextUtils.isEmpty(serverCache)) {
            String cacheControl = request.cacheControl().toString();
            if (TextUtils.isEmpty(cacheControl)) {
                // 如果请求接口中未设置cacheControl，则统一设置为一分钟
                int maxAge = 1 * 60; // 在线缓存在1分钟内可读取 单位:秒
                return response.newBuilder()
                        .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .build();
            } else {
                return response.newBuilder()
                        .addHeader("Cache-Control", cacheControl)
                        .removeHeader("Pragma")
                        .build();
            }
        }
//        }
        return response;
    }
}
